#!/usr/bin/env python
import time, sys, os

class PyHPExec ( object ):
	def __init__ ( self, pyhp ):
		self._pyhp = pyhp
		self.log = self._pyhp.log.getLogger ( "PyHP Exec" )

	def read ( self, fname ):
		self._pyhp.log.debug ( "PARSING: %s" % fname )
		
		if os.path.isfile ( fname ):
			self.parse ( file ( fname, "r" ).read () )
		else:
			self._pyhp.return_code = "404 Not found"
			
	def parse ( self, data ):
		import StringIO

		def _do_print ( html ):
			# CHECKME: forse ci vuole uno strip()
			if html:
				fout.write ( 'print """' + html + '""",' )

		fout = StringIO.StringIO ()

		x = 0
		y = 0
		y = data.find ( '<?pyhp', x )

		while y != -1:
			html = data [ x : y ]
			_do_print ( html )

			x = y + 6
			y = data.find ( '?>', x )
			code = data [ x : y ]
			fout.write ( code )

			x = y + 2
			y = data.find ( '<?pyhp', x )

		html = data [ x : y ]
		_do_print ( html )

		self.__exec ( fout.getvalue () )


	def __exec ( self, code ):
		# dizionario in cui eseguire il codice
    		environment_dict = {'__builtins__': __builtins__, 'pyhp': self._pyhp }

    		# eseguo il codice
    		try:
      			exec code in environment_dict
		except:
			raise


if __name__ == '__main__':
	class PyHP ( object ):
		def __init__ ( self ):
			class sess ( object ):
				def __init__ ( self ):
					self.data = {}

			self.session = sess ()

	px = PyHPExec ( PyHP () )

	px.read ( """
Hello World
this is a text
<?pyhp
print "Session output: "
for k,v in pyhp.session.data.iteritems ():
	print k, v
?>

CIao sono un testo
""" )
